package cn.yshujia.utils;

import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author YShuJia
 * @create 2024/12/16
 * @description SocketUtils
 */

@Component
public class SocketUtils {
	
	@Resource
	private SocketIOServer socketIoServer;
	
	/* 广播评论 */
	public void sendComment(Object message) {
		if (!ObjectUtils.isEmpty(message)) {
			// 广播评论
			socketIoServer.getNamespace("/comment")
					.getBroadcastOperations()
					.sendEvent("commentMessage", message);
		}
	}
	
	private static final Map<String, HashMap<UUID, SocketIOClient>> concurrentHashMap = new ConcurrentHashMap<>();
	
	/**
	 * @param userId:         用户ID
	 * @param sessionId:      页面sessionId
	 * @param socketIOClient: 面对应的通道连接
	 *                        [userId, sessionId, socketIOClient] * @return void
	 * @author YShuJia
	 * @description 缓存用户通道连接
	 * @create 2024/12/16 21:02
	 */
	public void saveClient(String userId, UUID sessionId, SocketIOClient socketIOClient) {
		HashMap<UUID, SocketIOClient> sessionIdClientCache = concurrentHashMap.get(userId);
		if (sessionIdClientCache == null) {
			sessionIdClientCache = new HashMap<>();
		}
		sessionIdClientCache.put(sessionId, socketIOClient);
		concurrentHashMap.put(userId, sessionIdClientCache);
	}
	
	/**
	 * @param userId: 用户 id
	 *                [userId] * @return HashMap<UUID,SocketIOClient>
	 * @author YShuJia
	 * @description 获取用户的页面通道信息
	 * @create 2024/12/16 21:02
	 */
	public HashMap<UUID, SocketIOClient> getUserClient(String userId) {
		return concurrentHashMap.get(userId);
	}
	
	/**
	 * @param userId:
	 * @param sessionId: [userId, sessionId] * @return void
	 * @author YShuJia
	 * @description 根据用户 id 及页面 sessionId 删除页面通道连接
	 * @create 2024/12/16 21:03
	 */
	public void deleteSessionClientByUserId(String userId, UUID sessionId) {
		concurrentHashMap.get(userId).remove(sessionId);
	}
	
	/**
	 * @param userId: [userId] * @return void
	 * @author YShuJia
	 * @description 根据用户 id 删除用户通道连接缓存
	 * @create 2024/12/16 21:04
	 */
	public void deleteUserCacheByUserId(String userId) {
		concurrentHashMap.remove(userId);
	}
}
